<template>
  <div class="profile-view">
    <div class="profile-container">
      <!-- 个人信息卡片 -->
      <div class="profile-card">
        <div class="profile-header">
          <h1>个人中心</h1>
          <p>管理你的个人信息和账户设置</p>
        </div>

        <!-- 头像和基本信息 -->
        <div class="avatar-section">
          <div class="avatar-container">
            <el-avatar :src="userStore.userAvatar" :size="100">
              {{ userStore.userName.charAt(0) }}
            </el-avatar>
            <el-button 
              :icon="Camera" 
              circle 
              class="avatar-edit-btn"
              @click="uploadAvatar"
            />
          </div>
          <div class="basic-info">
            <h2>{{ userStore.userInfo?.username }}</h2>
            <p>{{ userStore.userInfo?.college }}</p>
            <div class="join-time">
              加入时间：{{ formatTime(userStore.userInfo?.createdAt) }}
            </div>
          </div>
        </div>

        <!-- 个人信息表单 -->
        <el-form
          ref="profileFormRef"
          :model="profileForm"
          :rules="profileRules"
          label-width="100px"
          class="profile-form"
        >
          <el-form-item label="真实姓名" prop="username">
            <el-input v-model="profileForm.username" />
          </el-form-item>

          <el-form-item label="学校邮箱">
            <el-input v-model="profileForm.email" disabled />
          </el-form-item>

          <el-form-item label="学号">
            <el-input v-model="profileForm.studentId" disabled />
          </el-form-item>

          <el-form-item label="所在学院">
            <el-input v-model="profileForm.college" disabled />
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="profileForm.phone" />
          </el-form-item>

          <el-form-item>
            <el-button 
              type="primary" 
              @click="updateProfile"
              :loading="userStore.isLoading"
            >
              保存修改
            </el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 密码修改 -->
      <div class="password-card">
        <h3>修改密码</h3>
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
          class="password-form"
        >
          <el-form-item label="当前密码" prop="currentPassword">
            <el-input
              v-model="passwordForm.currentPassword"
              type="password"
              show-password
            />
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button 
              type="primary" 
              @click="changePassword"
              :loading="passwordLoading"
            >
              修改密码
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 账户统计 -->
    <div class="stats-sidebar">
      <div class="stats-card">
        <h3>账户统计</h3>
        <div class="stats-list">
          <div class="stats-item">
            <span class="stats-label">发布商品</span>
            <span class="stats-value">{{ accountStats.publishedGoods }}</span>
          </div>
          <div class="stats-item">
            <span class="stats-label">收藏商品</span>
            <span class="stats-value">{{ accountStats.collectedGoods }}</span>
          </div>
          <div class="stats-item">
            <span class="stats-label">总浏览量</span>
            <span class="stats-value">{{ accountStats.totalViews }}</span>
          </div>
          <div class="stats-item">
            <span class="stats-label">成功交易</span>
            <span class="stats-value">{{ accountStats.successfulTrades }}</span>
          </div>
        </div>
      </div>

      <!-- 快速操作 -->
      <div class="quick-actions">
        <h3>快速操作</h3>
        <div class="action-list">
          <el-button 
            type="primary" 
            :icon="Plus" 
            @click="$router.push('/publish')"
            class="action-btn"
          >
            发布商品
          </el-button>
          <el-button 
            :icon="Box" 
            @click="$router.push('/my-goods')"
            class="action-btn"
          >
            我的商品
          </el-button>
          <el-button 
            :icon="Star" 
            @click="$router.push('/collects')"
            class="action-btn"
          >
            我的收藏
          </el-button>
        </div>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="avatarDialogVisible" title="更换头像" width="400px">
      <ImageUpload 
        v-model="avatarImages"
        :max-count="1"
      />
      <template #footer>
        <el-button @click="avatarDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAvatar">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { userApi } from '@/api/user'
import { validatePhone, formatTime } from '@/utils/format'
import { ElMessage } from 'element-plus'
import ImageUpload from '@/components/ImageUpload.vue'
import { 
  Camera, 
  Plus, 
  Box, 
  Star 
} from '@element-plus/icons-vue'

const userStore = useUserStore()

// 表单引用
const profileFormRef = ref()
const passwordFormRef = ref()

// 个人信息表单
const profileForm = reactive({
  username: '',
  email: '',
  studentId: '',
  college: '',
  phone: ''
})

// 密码修改表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 头像相关
const avatarDialogVisible = ref(false)
const avatarImages = ref([])

// 加载状态
const passwordLoading = ref(false)

// 账户统计
const accountStats = ref({
  publishedGoods: 0,
  collectedGoods: 0,
  totalViews: 0,
  successfulTrades: 0
})

// 表单验证规则
const profileRules = {
  username: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在2到10个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!validatePhone(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 初始化表单数据
const initFormData = () => {
  if (userStore.userInfo) {
    profileForm.username = userStore.userInfo.username || ''
    profileForm.email = userStore.userInfo.email || ''
    profileForm.studentId = userStore.userInfo.studentId || ''
    profileForm.college = userStore.userInfo.college || ''
    profileForm.phone = userStore.userInfo.phone || ''
  }
}

// 监听用户信息变化
watch(() => userStore.userInfo, initFormData, { immediate: true })

// 更新个人信息
const updateProfile = async () => {
  if (!profileFormRef.value) return
  
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      const success = await userStore.updateProfile({
        username: profileForm.username,
        phone: profileForm.phone
      })
      
      if (success) {
        // 更新成功后重新获取用户信息
        await userStore.getUserInfo()
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  initFormData()
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        passwordLoading.value = true
        const response = await userApi.changePassword({
          currentPassword: passwordForm.currentPassword,
          newPassword: passwordForm.newPassword
        })
        
        if (response.code === 200) {
          ElMessage.success('密码修改成功')
          // 清空表单
          passwordForm.currentPassword = ''
          passwordForm.newPassword = ''
          passwordForm.confirmPassword = ''
          passwordFormRef.value.resetFields()
        } else {
          ElMessage.error(response.message || '密码修改失败')
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('密码修改失败，请重试')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 上传头像
const uploadAvatar = () => {
  avatarDialogVisible.value = true
}

// 保存头像
const saveAvatar = async () => {
  if (avatarImages.value.length === 0) {
    ElMessage.warning('请选择头像图片')
    return
  }

  const success = await userStore.updateProfile({
    avatar: avatarImages.value[0]
  })
  
  if (success) {
    avatarDialogVisible.value = false
    avatarImages.value = []
  }
}

// 获取账户统计
const getAccountStats = async () => {
  try {
    const response = await userApi.getUserStats()
    if (response.code === 200) {
      accountStats.value = response.data
    }
  } catch (error) {
    console.error('获取账户统计失败:', error)
  }
}

// 组件挂载时初始化
onMounted(() => {
  initFormData()
  getAccountStats()
})
</script>

<style scoped>
.profile-view {
  max-width: 1200px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
  align-items: start;
}

.profile-container {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.profile-card,
.password-card {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.profile-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.profile-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.profile-header p {
  color: #666;
  font-size: 14px;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
  border-radius: 12px;
}

.avatar-container {
  position: relative;
}

.avatar-edit-btn {
  position: absolute;
  bottom: -5px;
  right: -5px;
  background: #409eff;
  border-color: #409eff;
  color: white;
}

.basic-info h2 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.basic-info p {
  color: #666;
  margin-bottom: 8px;
}

.join-time {
  font-size: 12px;
  color: #999;
}

.password-card h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.stats-sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.stats-card,
.quick-actions {
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 20px;
}

.stats-card h3,
.quick-actions h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.stats-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.stats-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f8f9fa;
}

.stats-item:last-child {
  border-bottom: none;
}

.stats-label {
  color: #666;
  font-size: 14px;
}

.stats-value {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.action-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.action-btn {
  width: 100%;
  justify-content: flex-start;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-view {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .profile-card,
  .password-card {
    padding: 20px;
  }
  
  .avatar-section {
    flex-direction: column;
    text-align: center;
    gap: 15px;
  }
  
  .stats-sidebar {
    order: -1;
  }
  
  .stats-card,
  .quick-actions {
    position: static;
  }
  
  .action-list {
    flex-direction: row;
    flex-wrap: wrap;
  }
}
</style>